<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 2017/1/6
 * Time: 19:53
 */

namespace app\src\platform\logic;


use app\src\account\enmu\AccountEnmu;
use app\src\base\helper\ExceptionHelper;
use app\src\base\logic\BaseLogic;
use app\src\buyorder\logic\BuyOrderLogic;
use app\src\invite\action\InviteCodeAction;
use app\src\invite\logic\InviteCodeLogic;
use app\src\platform\emnu\PlatformType;
use app\src\platform\model\Platform;
use app\src\powersystem\enum\AdminRoleEnum;
use app\src\powersystem\logic\AuthGroupAccessLogic;
use app\src\system\logic\CityLogic;
use app\src\user\logic\UserMemberLogic;
use app\src\wallet\logic\WalletLogic;
use app\weixin\controller\Income;
use think\Db;
use think\exception\DbException;

class PlatformLogic extends BaseLogic{

    public function _init()
    {
        $this->setModel(new Platform());
    }

    /**
     * 根据平台权限创建平台
     * @param $platform_id
     * @param $entity
     */
    public function addPlatformWithPermission($platform_id, $platform_group, $parent_platform_id, $entity)
    {
        if($this->checkAddPermission($platform_id, $platform_group, $parent_platform_id)!==true){
            return $this->apiReturnErr('no permission to add platform');
        }
        return $this->addPlatform($parent_platform_id, $entity);
    }

    /**
     * 检查添加平台权限
     * @param $platform_id
     * @param $platform_group int 平台类型
     */
    protected function checkAddPermission($platform_id, $platform_group, $parent_platform_id)
    {
        //TODO check permission
        return true;
    }

    /**
     * 添加平台
     * @param $parent_id
     * @param $entity
     * @return array
     */
    public function addPlatform($parent_id, $entity)
    {

        $result = $this->getPlatformInfo($parent_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        $parent_info = $result['info'];
        $city_code = $province_code = '';
        switch ($entity['group_id']) {
            case PlatformType::PROVINCE_SERVICE:
                $province_code = $entity['province_code'];
                break;
            case PlatformType::CITY_SERVICE:
                $province_code = $parent_info['province_code'];
                $city_code = $entity['city_code'];
                //判断是否父级所属省
                $result = (new CityLogic)->getInfo(['father' => $province_code, 'cityID' => $city_code]);
                if(!$result['status']) return $this->apiReturnErr($result['info']);
                if(empty($result['info'])) return $this->apiReturnErr('该市不是目标平台下级市');
                break;
            case PlatformType::PERSONAL:
                $city_code = $parent_info['city_code'];
                $province_code = $parent_info['province_code'];
                break;
        }
        $data = [
            'group_id' => $entity['group_id'],
            'parent_id' => $parent_id,
            'name' => $entity['name'],
            'city_code' => $city_code,
            'province_code' => $province_code,
            'other_info' => isset($entity['other_info']) ? $entity['other_info']: '',
            'preferential_money' => isset($entity['preferential_money']) ? $entity['preferential_money']: 0,
            'create_time' => NOW_TIME,
            'status' => 0
        ];
        $result = $this->add($data);
        if($result['status']){

            //添加邀请码
            $platform_id = $result['info'];
            (new InviteCodeLogic)->create(AccountEnmu::PLATFORM, $platform_id);

            return $this->apiReturnSuc($platform_id);
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 获取所有父级平台id
     * @param $platform_id
     */
    public function getParents($platform_id)
    {
        $list = [];
        $parent_id = $platform_id;
        do {
            $result = $this->getPlatformInfo($parent_id);

            if(!$result['status']){
                return $this->apiReturnErr($result['info']);
            }

            if(empty($result['info'])){
                return $this->apiReturnErr('error: getParents,empty parent');
            }
            $parent_id = $result['info']['parent_id'];

            $list[] = $result['info'];

        } while ($parent_id > 0);

        return $this->apiReturnSuc($list);
    }

    /**
     * 判断该平台是否正常（未被删除）
     * @param $platform_id
     * @return bool
     */
    public function checkPlatform($platform_id)
    {
        $map = [
            'id' => $platform_id,
            'status' => 0
        ];
        $result = $this->getInfo($map);
        if(!$result['status']) return $result['info'];
        if(!empty($result['info'])){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取正常状态平台（未被删除）
     * @param $platform_id
     * @return array
     */
    public function getPlatformInfo($platform_id)
    {
        try{
            $map = [
                'plat.id' => $platform_id,
                'plat.status' => 0
            ];

            //获取城市 省
            $model = $this->getModel();
            $result = $model->alias('plat')->field('plat.*,cc.city,cp.province,plat2.name as parent_name')
                ->join(['common_city' => 'cc'], 'plat.city_code = cc.cityID', 'LEFT')->join(['common_province' => 'cp'], 'plat.province_code = cp.provinceID', 'LEFT')
                ->join('__PLATFORM__ plat2', 'plat.parent_id = plat2.id', 'LEFT')
                ->where($map)->find();

            if(empty($result)) return $this->apiReturnErr('error platform');

            return $this->apiReturnSuc($result);
        }catch (DbException $ex){
            return $this->apiReturnErr(ExceptionHelper::getErrorString($ex));
        }


    }

    /**
     * 设置指定平台管理员
     * @param $platform_id
     * @param $uid
     * @return array
     */
    public function setPlatformAdmin($platform_id, $uid)
    {
        $result = $this->getPlatformInfo($platform_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if(empty($result['info'])) return $this->apiReturnErr('error platform');
        $platform_info = $result['info'];

        $PlatformAdminLogic = new PlatformAdminLogic();
        //判断是否已有
        $map = ['platform_id' => $platform_id, 'uid' => $uid];
        $result = $PlatformAdminLogic->getInfo($map);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if(!empty($result['info'])) return $this->apiReturnSuc('success');

        $entity = [
            'platform_id' => $platform_id,
            'uid' => $uid
        ];
        $result = $PlatformAdminLogic->saveAll([$entity]);
        if($result['status']){
            //添加角色
            $role_code = "";
            if($platform_info['group_id'] == PlatformType::PERSONAL){
                $role_code = AdminRoleEnum::ROLE_Personal;
            }
            if($platform_info['group_id'] == PlatformType::CITY_SERVICE){
                $role_code = AdminRoleEnum::ROLE_CityService;
            }
            if($platform_info['group_id'] == PlatformType::PROVINCE_SERVICE){
                $role_code = AdminRoleEnum::ROLE_ProvinceService;
            }
            if($platform_info['group_id'] == PlatformType::HEADQUARTERS){
                $role_code = AdminRoleEnum::ROLE_Service;
            }
            (new AuthGroupAccessLogic)->addRole($uid, $role_code);
            return $this->apiReturnSuc('success');
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 移除指定平台管理员
     * @param $platform_id
     * @param $uid
     * @return array
     */
    public function removePlatformAdmin($platform_id, $uid)
    {
        if($this->checkPlatform($platform_id)!==true) return $this->apiReturnErr('error platform');
        $map = [
            'platform_id' => $platform_id,
            'uid' => $uid
        ];
        $result = (new PlatformAdminLogic)->delete($map);
        if($result['status']){
            return $this->apiReturnSuc('success');
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 下级平台全部
     * @param $platform_id
     * @return array
     * @return array
     */
    public function childAll($platform_id)
    {
        if($this->checkPlatform($platform_id) !== true) return $this->apiReturnErr('error platform');
        $map = [
            'parent_id' => $platform_id,
            'status' => 0
        ];
        $result = $this->queryNoPaging($map);

        return $result;

    }

    /**
     * 获取指定平台所有管理员
     * @param $platform_id
     * @return array
     */
    public function queryAllAdmin($platform_id)
    {
        try{
            if($this->checkPlatform($platform_id) !== true) return $this->apiReturnErr('error platform');
            $model = (new PlatformAdminLogic)->getModel();
            $map = [
                'pa.platform_id' => $platform_id
            ];
            $result = $model->alias('pa')->field('pa.*,u.mobile,u.nickname')
                ->join(['v_user_info' => 'u'], 'pa.uid = u.id')->where($map)->select();
            return $this->apiReturnSuc($result);
        }catch (DbException $ex){
            return $this->apiReturnErr(ExceptionHelper::getErrorString($ex));
        }

    }

    /**
     * 删除平台
     * @param $platform_id
     * @return array
     */
    public function deletePlatform($platform_id)
    {
        if($this->checkPlatform($platform_id) !== true) return $this->apiReturnErr('error platform');

        Db::startTrans();
        try{
            $map = ['id' => $platform_id];
            $result = $this->pretendDelete($map);

            if(!$result['status']){
                Db::rollback();
                return $result['info'];
            }

            //移除管理员
            $map = [
                'platform_id' => $platform_id
            ];
            $result  = (new PlatformAdminLogic)->delete($map);

            if(!$result['status']){
                Db::rollback();
                return $result['info'];
            }

            Db::commit();

            return $this->apiReturnSuc('success');

        }catch (DbException $ex){
            Db::rollback();
            return $this->apiReturnErr(ExceptionHelper::getErrorString($ex));
        }

    }

}